package com.github.tommas.decompiler;

import org.jboss.windup.decompiler.fernflower.FernFlowerResultSaver;
import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler;
import org.jetbrains.java.decompiler.main.decompiler.PrintStreamLogger;
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FernFlowerDecompiler implements Decompiler {
    private final File root;
    public FernFlowerDecompiler(String rootDir) {
        this.root = new File(rootDir);
    }
    @Override
    public void decompile(String className, byte[] classfileBuffer) {
        File dir = new File(className + ".class");
        FernFlowerResultSaver saver = new FernFlowerResultSaver(List.of(className), root, null);
        BaseDecompiler decompiler = new BaseDecompiler(new IBytecodeProvider() {
            @Override
            public byte[] getBytecode(String externalPath, String internalPath) throws IOException {
                return classfileBuffer;
            }
        }, saver, null, new PrintStreamLogger(System.out));
        try {
            decompiler.addSpace(dir, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        decompiler.decompileContext();
    }
}
